package com.example.myapp.Activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.WX_Posts_Adapter;
import com.example.myapp.Listviewloading.MyFooterAdapter;
import com.example.myapp.Listviewloading.MyHeaderAdapter;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnFooterRefreshListener;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class Myhome extends AppCompatActivity {
    private ImageView myhome_back;
    private TextView myhome_username;
    private TextView myhome_jianjie;
    private TextView myhome_count1;
    private TextView myhome_edit;
    private CircleImageView myhome_head_image;
    private MyData mydata;
    private int p4 = R.id.settings_tab;
    private List<String> listarr = new ArrayList<>();
    private ShapeLoadingDialog shapeLoadingDialog;


    private UltimateRefreshView mUltimateRefreshView;
    private int page = 0;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String updatatime="";
    private RecyclerView recyclerView;
    private WX_Posts_Adapter adapter;
    private List<Article> postsList = new ArrayList<>();
    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: {
                    init();// 页面初始化
                    queryALLPost();
                    break;
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().addActivity(this);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_myhome);
        myhome_back = findViewById(R.id.myhome_back);
        myhome_username = findViewById(R.id.myhome_username);
        myhome_head_image = findViewById(R.id.myhome_head_image);
        myhome_jianjie = findViewById(R.id.myhome_jianjie);
        myhome_edit = findViewById(R.id.myhome_edit);
        mydata = (MyData) getApplication();

        mUltimateRefreshView = (UltimateRefreshView)findViewById(R.id.refreshView);
        recyclerView= findViewById(R.id.mypostslistview);
        mUltimateRefreshView.setBaseHeaderAdapter(new MyHeaderAdapter(Myhome.this));




        /**底部上拉加载*/
        mUltimateRefreshView.setBaseFooterAdapter(new MyFooterAdapter(Myhome.this));

        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {

                mUltimateRefreshView.onHeaderRefreshComplete();
            }
        });


        /**底部上拉加载事件*/
        mUltimateRefreshView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
            @Override
            public void onFooterRefresh(UltimateRefreshView view) {
                page++;
                BmobQuery<Article> query = new BmobQuery<>();
                query.addWhereEqualTo("author", BmobUser.getCurrentUser(User.class));
                query.setSkip(page*5); // 忽略前10条数据（即第一页数据结果）
                query.setLimit(5); // 限制最多10条数据结果作为一页
                //包含作者信息
                query.include("author");
                query.order("-orderTime");
                query.findObjects(new FindListener<Article>() {
                    @Override
                    public void done(List<Article> object, BmobException e) {
                        if (e == null) {
                            if (object.size()>0){
                                postsList.addAll(object);
                                adapter.notifyDataSetChanged();
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }else {
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }
                        } else {
                            Log.e("aaaa","查询我的动态失败"+ e.getMessage());
                            mUltimateRefreshView.onFooterRefreshComplete();
                        }
                    }

                });



            }
        });





        myhome_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(Myhome.this, Main.class);
//                intent.putExtra("page", p4);//打开主页
//                startActivity(intent);
                finish();
            }
        });
        myhome_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Myhome.this, EditUser.class));
                finish();
            }
        });


        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);
    }

    @Override
    public void onBackPressed() {
        //此处写退向后台的处理
        finish();
        Log.w("aaaa", "我点击返回键！");
    }//手机返回键

    //页面初始化
    private void init() {
        String username = mydata.getUserName();
        myhome_username.setText(username);
        myhome_jianjie.setText("简介：" + mydata.getShow());
        Glide.with(Myhome.this).load(mydata.getIconUrl()).into(myhome_head_image);
    }

    /**
     * 查询一对多，我的所有动态
     */
    private void queryALLPost() {

        if (BmobUser.isLogin()) {

            Date date = new Date(System.currentTimeMillis());
            updatatime= simpleDateFormat.format(date);
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            BmobQuery<Article> query = new BmobQuery<>();
            query.addWhereEqualTo("author", new BmobPointer(BmobUser.getCurrentUser(User.class)));
            query.setLimit(8); // 限制最多10条数据结果作为一页
            //包含作者信息
            query.include("author");
            query.order("-orderTime");
            query.findObjects(new FindListener<Article>() {
                @Override
                public void done(List<Article> object, BmobException e) {
                    if (e == null) {
                        postsList=object;
                        if(postsList.size()>0){
                            LinearLayoutManager layoutManager = new LinearLayoutManager(Myhome.this);//正常listview
                            recyclerView.setLayoutManager(layoutManager);
                            recyclerView.setItemViewCacheSize(500);
                            adapter =new WX_Posts_Adapter(Myhome.this, postsList);
                            recyclerView.setAdapter(adapter);
                            Log.w("bmob", "成功找到我发布的帖子！"+object.size());
                        }

                    } else {
                        Log.e("aaaa", "查询我的动态失败" + e.getMessage());
                    }
                }

            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }

    //网络加载
    private void openLoading() {
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(Myhome.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }

    //关闭网络加载
    private void closeLoading() {
        shapeLoadingDialog.dismiss();
    }
}